#!/bin/sh

cpath=$1
nsid=$2
ouser=$3
oraHome=$4
dbfsPath=$5

if [ "$#" -lt 4 ]; then
 echo "This script needs min 4 input parameter"
 echo "usage: recoverRman.sh <Catalog path> <New database sid name><oracle OS user><oracle home> "
exit 1
fi
ORACLE_HOME=$oraHome
PATH=$ORACLE_HOME/bin:$PATH
ORACLE_SID=$nsid
export ORACLE_SID
export ORACLE_HOME
export PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib
export LD_LIBRARY_PATH

scriptsRoot=${LB_ROOT}
if [ -z "$scriptsRoot" ];then
    echo "missing env LB_ROOT"
    exit 1
fi

. ${scriptsRoot}/oracle/oracleclone/OracleAppMountComFunc.sh

dbrecover="dbrecover_"$nsid".txt"
change_own $ouser $dbrecover

if [ -z "$rmanchannels" ]; then
rmanchannels=4;
fi

allocatech=
releasech=
i=0
while [ $i -lt "$rmanchannels" ]; do
if [ -z "$allocatech" ]; then
allocatech="allocate channel d$i device type disk;"
releasech="release channel d$i;"
else
allocatech=$allocatech"allocate channel d$i device type disk;"
releasech=$releasech"release channel d$i;"
fi
i=`expr $i + 1`
done

if [ ! -f "$dbfsPath" ]; then
  roTBS=''
else
 roTBS=`cat $dbfsPath`
fi

if [ "$pdbcnt" -gt "0" ]; then
  if [ ! -z "$roTBS" ]; then
    recoverCMD="skip tablespace "pdb$seed":SYSTEM, "pdb$seed":SYSAUX, "pdb$seed":UNDOTBS1, "pdb$seed":UNDOTBS2,$roTBS"
  else
    recoverCMD='skip tablespace "pdb$seed":SYSTEM, "pdb$seed":SYSAUX, "pdb$seed":UNDOTBS1, "pdb$seed":UNDOTBS2'
  fi
else
  if [ ! -z "$roTBS" ]; then
     recoverCMD="skip tablespace $roTBS"
  else
    recoverCMD=''
  fi
fi


echo "******* recovering database *********** "

rmancmd="run
{
$allocatech
catalog start with '$cpath/archivelog' noprompt;
recover database $recoverCMD;
$releasech
}"

echo $rmancmd

su $ouser -c "$ORACLE_HOME/bin/rman target / log $dbrecover  " << EOF
$rmancmd
exit
EOF
